package soar.template.springboot2.websocket.server.service;

import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@ServerEndpoint(value = "/player")
@Component
public class Player
{
    private static final Logger logger = LoggerFactory.getLogger(Player.class);

    private static CopyOnWriteArraySet<Player> players = new CopyOnWriteArraySet<>();

    private Session session;

    @OnOpen
    public void onOpen(Session session)
    {
        this.session = session;
        players.add(this);
        logger.info("new connection, total: {}", players.size());
    }

    @OnClose
    public void onClose()
    {
        players.remove(this);
        logger.info("close connection, total: {}", players.size());
    }

    @OnMessage
    public void onMessage(String message, Session session)
    {
        broadcastMessage(message);
        logger.info("receive: {}", message);
    }

    @OnError
    public void onError(Session session, Throwable error)
    {
        logger.error("error: {}", error.getMessage());
    }

    public void sendMessage(String message)
    {
        try
        {
            this.session.getBasicRemote().sendText(message);
        }
        catch (Exception e)
        {
            logger.error("{}", e.getMessage());
        }
    }

    public static void broadcastMessage(String message)
    {
        String msg = String.format("%s, total: %d", message, players.size());
        for (Player player : players)
        {
            player.sendMessage(msg);
        }
    }
}
